<?php

namespace App\Http\Controllers\Health;

use App\Health;
use App\Http\Controllers\UserController;
use App\Sleep;
use App\Sports;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Input;
class HealthController extends Controller
{

    private $user;

    /**
     * HealthController constructor.
     */
    public function __construct()
    {
        $u=new UserController();
        $this->user=$u->getCurrentUser()['name'];
    }


    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $health=$this->getHealthData(Carbon::today()->toDateString());
        return view('health.index')->with('name',$this->user)->with(array(
            "height"=>$health['height'],
            "weight"=>$health['weight'],
            "blood_pressure"=>$health['blood_pressure'],
            "heart_rate"=>$health['heart_rate'],
        ));
    }


    /**
     * Display view of sports data.
     *
     * @return \Illuminate\Http\Response
     */
    public function showSports()
    {
        $sports=$this->getSportsData(Carbon::today()->toDateString());
        return view('health.sports')->with('name',$this->user)->with(array(
            "distance"=>$sports['distance'],
            "time"=>$sports['time'],
            "heat"=>$sports['heat'],
            "steps"=>$sports['steps']
        ));
    }


    public function showTrend()
    {
        return redirect('/health/trend/weight/7');
       // return view('health.trend')->with('name',$this->user);
    }

    /**
     * Display view of weight trend
     *
     * @return \Illuminate\Http\Response
     */
    public function  showWeightTrend($days)
    {
        if($days!=7&&$days!=30&&$days!=60)
        {
            abort(404);
        }
       if(Health::count()>=$days){
           $tmp=Health::where('user',$this->user)->orderBy('date','desc')->take($days)->get();
            $health=array_reverse($tmp->toArray());
       }else{
           $health=Health::where('user',$this->user)->orderBy('date')->get();
       }
        return view('health.trend-weight')->with('name',$this->user)->with("health",$health)->with("days",$days);
    }

    /**
     * Display view of blood_pressure trend
     *
     * @return \Illuminate\Http\Response
     */
    public function  showBloodPressureTrend($days)
    {
        if($days!=7&&$days!=30&&$days!=60)
        {
            abort(404);
        }
        if(Health::count()>=$days){
            $tmp=Health::where('user',$this->user)->orderBy('date','desc')->take($days)->get();
            $health=array_reverse($tmp->toArray());
        }else{
            $health=Health::where('user',$this->user)->orderBy('date')->get();
        }
        return view('health.trend-blood_pressure')->with('name',$this->user)->with("health",$health)->with("days",$days);
    }

    /**
     * Display view of weight trend
     *
     * @return \Illuminate\Http\Response
     */
    public function  showSportsTrend($days)
    {
        if($days!=7&&$days!=30&&$days!=60)
        {
            abort(404);
        }
        if(Sports::count()>=$days){
            $tmp=Sports::where('user',$this->user)->orderBy('date','desc')->take($days)->get();
            $sports=array_reverse($tmp->toArray());
        }else{
            $sports=Sports::where('user',$this->user)->orderBy('date')->get();
        }
        return view('health.trend-sports')->with('name',$this->user)->with("sports",$sports)->with("days",$days);
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    /**
     *
     */
    public function showUpload()
    {

    }

    /**
     * read xml file
     * @param $file
     * @return SimpleXMLElement
     */
    private function readXml($file)
    {
       return simplexml_load_string($file);
    }

    public function save($file)
    {
        //$data=$this->readXml(Storage::get('healthData/example.xml'));
        $data=$this->readXml(Storage::get($file));
        Health::create([
            "user"=>$data->user,
            "date"=>$data->date,
            "height"=>$data->health->height,
            "weight"=>$data->health->weight,
            "blood_pressure"=>$data->health->blood_pressure,
            "heart_rate"=>$data->health->heart_rate
        ]);
        Sports::create([
            "user"=>$data->user,
            "date"=>$data->date,
            "distance"=>$data->sports->distance,
            "time"=>$data->sports->time,
            "heat"=>$data->sports->heat,
            "steps"=>$data->sports->steps
        ]);
    }


    public function makeHealthData()
    {
        $user=['ivan'];$n=count($user);
        $start=Carbon::createFromDate(2015,11,4);
        $end=Carbon::createFromDate(2015,11,8)->toDateString();
        $title="<?xml version=\"1.0\" encoding=\"utf-8\"?>";
        for($i=0;$i<$n;$i++)
        {
            $start=$start->addDay(1);
            while($start->toDateString()!=$end){
                $file='healthData/'.$user[$i].'_'.$start->toDateString();
                if(!Storage::exists($file))
                {
                    $content=$title."";
                    Storage::put($file,$content);
                }
        }
        }

    }

    /**
     * get data by date via ajax
     *
     * @return \Illuminate\Http\Response
     */
    public function getSportsDataAjax()
    {
        return response()->json($this->getSportsData(Input::get('date')));
    }

    /**
     * get data by date via ajax
     *
     * @return \Illuminate\Http\Response
     */
    public function getDataAjax()
    {
        return response()->json($this->getHealthData(Input::get('date')));
    }


    /**
     * get data by date
     *
     * @return array
     */
    private function getHealthData($date){
        $healthData=Health::where(['date'=>$date,'user'=>$this->user])->first();
        if($healthData==null){
            return array(
                "height"=>"",
                "weight"=>"",
                "blood_pressure"=>"",
                "heart_rate"=>""
            );
        }
        return $healthData;
    }
    
    public function getBloodPressureRecently($days){
    	return $healthData=Health::query("select health.blood_pressure from health where `user`='".$this->user."' order by `date` desc limit 0,".$days.";")->get();
    }
    
    public function getHeartRateRecently($days){
    	return $healthData=Health::query("select health.heart_rate from health where `user`='".$this->user."' order by `date` desc limit 0,".$days.";")->get();
    }

    public function getSportTimeRecently($days){
    	return $sportsData=Sports::query("SELECT sports.`time` FROM sports where `user`='".$this->user."' order by `date` desc limit 0,".$days.";")->get();
    }
    
    /**
     * get sports data by date
     *
     * @return array
     */
    private function getSportsData($date){
        $sportsData=Sports::where(['date'=>$date,'user'=>$this->user])->first();
        if($sportsData==null){
            return array(
                "distance"=>"",
                "time"=>"",
                "heat"=>"",
                "steps"=>""
            );
        }
        return $sportsData;
    }


    public function getAllHealthData($user)
    {
        return Health::where('user',$user)->orderBy('date','desc');
    }

    public function getAllSportsData($user)
    {
        return Sports::where('user',$user)->orderBy('date','desc');
    }

}